// 公共的代码
// 参数date=new Date()
// type  yy:mm:dd  hh:mm:ss
const formatTime = (date, type ) => {
    date = new Date(date.replace(/\-/g, "/"))
    let str =  type.indexOf('/') > -1  ?  '/' : '-'
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const hour = date.getHours();
	const minute = date.getMinutes();
    const second = date.getSeconds();
    
    let  arr =  type.indexOf('ss') > -1 ?  [ hour, minute, second ]  : [ hour, minute]
	return (
		[ year, month, day ].map(formatNumber).join(str) + ' ' + arr.map(formatNumber).join(':')
	);
};

const formatNumber = (n) => {
	n = n.toString();
	return n[1] ? n : '0' + n;
};

//  s为金额； n 为几位小数 , 1,333.00
const onFmoney = function(s, n) {
	var n = n > 0 && n <= 20 ? n : 2;
	var s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(n) + '';
	var l = s.split('.')[0].split('').reverse(),
		r = s.split('.')[1];
	var t = '';
	for (var i = 0; i < l.length; i++) {
		t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? ',' : '');
	}
	return t.split('').reverse().join('') + '.' + r;
};

/**
 * 触发上一个页面的方法
 * delta 退回几层
 * method 方法名称
 * status, true 回退，false不回退
 * */
const triggerPrePagefun = (delta, method, params, status) => {
    const pages = getCurrentPages();
    status = status ||  status == undefined ? true :  false;
	if (pages.length > 1 ) {
        if(status){
            const prePage = pages[pages.length - delta - 1];
            prePage.$vm[`${method}`](params);       //触发父页面中的方法
            uni.navigateBack({ delta:Number(delta)  });
        }else{
            const prePage = pages[pages.length- delta - 1];
            prePage.$vm[`${method}`](params);       //触发父页面中的方法
        }
    }
};

//   url 错误页面的相对路径
const toErroPage = (url) => {
	uni.stopPullDownRefresh();
	uni.navigateTo({
		url: url,
		animationDuration: 200,
		animationType: 'pop-in'
	});
};

/**
 *  判断文件类型 ， 缺陷mimeType 不能确保唯一性
 */
const mimeTypejup = (mimeType) => {
	let type = '';
	var mimeTypeArr = {
		img: [ 'image/png', 'image/jpeg', 'image/bmp', 'image/jpeg', 'image/gif','img' ],
		excel: [ 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ],
		ppt: [
			'application/vnd.ms-powerpoint',
			'application/vnd.openxmlformats-officedocument.presentationml.presentation'
		],
		word: [ 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ],
		text: ['text/plain'],
		pdf: [ 'application/pdf' ],
		ZIPRAR: [ 'application/x-zip-compressed', 'application/zip', 'application/x-rar-compressed' ],
        video: [ 
        'video/3gpp2',
        'video/3gpp',
        'video/mpeg',
        'video/mp4', 
        'video/mpeg', 
        'video/x-m4v', 
        'video/mpeg',
        'video/quicktime', 
        'video/x-msvideo',
        'video/vnd.mpegurl',
        'video/x-mng',
        'video/x-ms-wm',
        'video/x-ms-wmv',
        'video/x-ms-wmx',
        'video/x-matroska',
        'video/x-sgi-movie',
        'video/x-ms-wvx',
        'video/x-msvideo',
        'video/avi',
        'video',
        'video/x-flv',
        'application/vnd.apple.mpegurl' ],
		audio: [
			'audio/x-mpeg',
			'audio/x-mpeg',
			'audio/x-mpegurl',
			'audio/mpeg',
			'audio/mp4a-latm',
			'audio/mp4a-latm',
			'audio/mp4a-latm',
			'audio/x-ms-wma',
			'audio/x-ms-wmv',
			'audio/x-pn-realaudio',
            'audio/x-wav',
            'application/vnd.smaf',
            'application/octet-stream',
            'application/vnd.nokia.configuration-message'
		],
		html: [ 'text/html',  ],
		other: [ '*/*', 'application/x-msdownload', ],
		all: []
	};
    
    mimeTypeArr.all = [
        ...mimeTypeArr.img,
        ...mimeTypeArr.excel,
        ...mimeTypeArr.ppt,
        ...mimeTypeArr.word,
        ...mimeTypeArr.text,
        ...mimeTypeArr.pdf,
        ...mimeTypeArr.ZIPRAR,
        ...mimeTypeArr.video,
        ...mimeTypeArr.audio,
        ...mimeTypeArr.html,
        ...mimeTypeArr.other
    ];
	for (var key in mimeTypeArr) {

        if(mimeType){
            if( key != 'video' && key != 'audio' && key != 'all' &&  mimeTypeArr[key].indexOf(mimeType)>-1){
                return type  =  key
            }else if(key == 'video' &&  (mimeTypeArr[key].indexOf(mimeType)>-1 ||  mimeType.indexOf('video')>-1)){
                return type  =  key
            }else if(key == 'audio' &&  (mimeTypeArr[key].indexOf(mimeType)>-1 ||  mimeType.indexOf('audio')>-1 ) ){
                return type  =  key
            }else if( key == "all" &&  mimeTypeArr[key].indexOf(mimeType) == -1){
                return type  =  'other'
            }
        }else{
            return type  =  'other'
        }
	}
};


/**
 * 划分文件类型
 * name 文件名 ， 如 图片.jpg
 * 
 * */ 
const  fileType=(name)=>{
    var mimeType = name ?  '.' + name.substring(name.lastIndexOf('.') + 1).toLowerCase() : ''; //截取文件后缀
    let type = '';
	var mimeTypeArr = {
		img: [ '.png', '.jpeg', '.bmp',  '.gif', '.jpg', '.svg'],
		excel: [ '.xls', '.xlsx', '.csv' ],
		ppt: [
			'.ppt', '.pptx'
		],
		word: [ '.doc', '.docx' ],
		text: [ '.text' ],
		pdf: [ '.pdf' ],
		ZIPRAR: [ '.zip', '.rar' ,'.arj', '.gz','.7z'],
        video: [ 
        '.wmv','.asf','.asx','.rm', '.remvb', '.3gp', '.mov','.m4v', '.avi',
        '.dat','.mkv','.flv','.vob','.mp4', '.webm' ],
		audio: [
			'.mp3','.wma','.wav','.ape','.flac','.ogg','.aac',
		],
		html: [ '.url', '.html' ],
		other: [ '.exe', '.md', ],
		all: []
	};

	mimeTypeArr.all = [
		...mimeTypeArr.img,
		...mimeTypeArr.excel,
		...mimeTypeArr.ppt,
		...mimeTypeArr.word,
		...mimeTypeArr.text,
		...mimeTypeArr.pdf,
		...mimeTypeArr.ZIPRAR,
		...mimeTypeArr.video,
		...mimeTypeArr.audio,
		...mimeTypeArr.html,
		...mimeTypeArr.other
	];
	for (var key in mimeTypeArr) {
		if (key != 'all' && mimeTypeArr[key].indexOf(mimeType) > -1) {
			return (type = key);
		} else if (key == 'all' && mimeTypeArr[key].indexOf(mimeType) == -1) {  //没有列出的都归为其他
			return (type = 'other');
		}
	}
}


/**
  * 获取 url 参数，不传name返回所有值，否则返回对应值
  * @name,字符串， search "?name=1&b=2"
  * @return
  */
let getUrlParams = function(name, search) {
	//
	// var url = window.location.search;
	var url = `?${search.split('?')[1]}`;
	if (url.indexOf('?') == 1) {
		return false;
	}
	url = url.substr(1);
	url = url.split('&');
	var name = name || '';
	var nameres;
	// 获取全部参数及其值
	for (var i = 0; i < url.length; i++) {
		var info = url[i].split('=');
		var obj = {};
		obj[info[0]] = decodeURI(info[1]);
		url[i] = obj;
	}
	// 如果传入一个参数名称，就匹配其值
	if (name) {
		for (var i = 0; i < url.length; i++) {
			for (const key in url[i]) {
				if (key == name) {
					nameres = url[i][key];
				}
			}
		}
	} else {
		nameres = url;
	}
	// 返回结果
	return nameres;
};

/**
  * convertObj， 对象拼接 url 参数
  * @param data, 对象
  * @returns
  */
let turnUrlData = function(data) {
	var _result = [];
	for (var key in data) {
		var value = data[key];
		if (value.constructor == Array) {
			value.forEach(function(_value) {
				_result.push(key + '=' + _value);
			});
		} else {
			_result.push(key + '=' + value);
		}
	}
	return _result.join('&');
};

/**
  * delObjKey， 删除对象的key及值
  * @param  obj, 数据对象
  * @param  key值是null或者是"", 删掉
  * @returns
  */
let delobjKey = (obj) => {
	for (var i in obj) {
		if (!obj[i]) {
			delete obj[i];
		}
	}
	return obj;
};

const diffTime = (oldS, newS) => {
	// .replace(/\-/g, "/") 兼容ios  要换格式
	var new_date = newS ? new Date(newS) : new Date(); //新建一个日期对象，默认现在的时间
	var old_date = oldS ? new Date(oldS) : new Date(); //设置过去的一个时间点，"yyyy-MM-dd HH:mm:ss"格式化日期
	var difftime = (new_date.getTime() - old_date.getTime()) / 1000; //计算时间差
	if (difftime < 0) {
		//服务器时间和北京时间不同步，导致时间差为负数
		difftime = 0;
    }
	var days = parseInt(difftime / 86400); // 天  24*60*60*1000
	var hours = parseInt(difftime / 3600) - 24 * days; // 小时 60*60 总小时数-过去的小时数=现在的小时数
	var minutes = parseInt((difftime % 3600) / 60); // 分钟 -(day*24) 以60秒为一整份 取余 剩下秒数 秒数/60 就是分钟数
	var seconds = parseInt(difftime % 60); // 以60秒为一整份 取余 剩下秒数

	return {
		days: days,
		hours: hours,
		minutes: minutes,
		seconds: seconds
	};
};

const diffTime1 = (oldS, newS) => {
	// .replace(/\-/g, "/") 兼容ios  要换格式
	var new_date = newS ? new Date(newS) : new Date(); //新建一个日期对象，默认现在的时间
	var old_date = oldS ? new Date(oldS) : new Date(); //设置过去的一个时间点，"yyyy-MM-dd HH:mm:ss"格式化日期
	var difftime = (old_date.getTime() - new_date.getTime()) / 1000; //计算时间差

	var days = parseInt(difftime / 86400); // 天  24*60*60*1000
	var hours = parseInt(difftime / 3600) - 24 * days; // 小时 60*60 总小时数-过去的小时数=现在的小时数
	var minutes = parseInt((difftime % 3600) / 60); // 分钟 -(day*24) 以60秒为一整份 取余 剩下秒数 秒数/60 就是分钟数
	var seconds = parseInt(difftime % 60); // 以60秒为一整份 取余 剩下秒数

	return {
		days: days,
		hours: hours,
		minutes: minutes,
		seconds: seconds
	};
};

/**
  * setTimer，轮询
  * @param  fun(), 方法， 通过页面this.fun获取方法
  * @param interval， 执行间隔
  * @resolve  返回下标， 便于页面调用clearTimer(index)  清除轮询
  */

let timer = [];
let setTimer = (fun, interval, name, params) => {
	return new Promise((resolve, reject) => {
		// var  str = 'timer' + timer[timer.length-1]
		var i = timer.findIndex((value) => value.name == name);
		if (i == -1) {
			var str = setInterval(function() {
				// 设置定时器
				fun(params);
			}, interval);
			timer.push({
				name: name,
				str: str
			});
			resolve(timer.length - 1); //传回下标，根据下标清除轮询
		} else {
			clearInterval(timer[i].str);
			//  timer[i].str = null
			timer = removeArr('current', timer, i);
			var str = setInterval(function() {
				// 设置定时器
				fun(params);
			}, interval);
			timer[i].str = str;
			resolve(i); //传回下标，根据下标清除轮询
		}
	});
};

// 清除轮询
let clearTimer = (index) => {
	clearInterval(timer[index].str);
	// timer[index].str = null
	timer = removeArr('current', timer, index);
};

// 判断姓名并截取字符串
let subStrName = (name) => {
    // 中文名
    var chinese = /^[\u4E00-\u9FA5]+(·[\u4E00-\u9FA5]+)*$/;
    //英文
    var eng = /^[a-zA-Z\s]{2,20}$/;
    if (chinese.test(name)) {
        return  name ?  name.substring(name.length - 2, name.length) :  ''
    } else if (eng.test(name)) {
        return name ?  name.substring(0, 2) :  '' 
    } else{
        return name ?  name.substring(0, 2) :  '' 
    }
  };

/****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
const randomString = (len) => {
	len = len || 32;
	var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
	var maxPos = $chars.length;
	var str = '';
	for (let i = 0; i < len; i++) {
		str += $chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return str;
};

//  size , '8164674';  
//  数据容量单位转换(kb,mb,gb,tb)
//  传入kb
const bytesToSize = (bytes) => {
	if (bytes === 0) return '0B';
	const k = 1024; // 1000 or 1024
	const sizes = [ 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' ];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
	return `${(bytes / Math.pow(k, i)).toPrecision(3)} ${sizes[i]}`;
};

// 删除指定下标的元素，返回新数组
// var a = [1, 2, 3, 4, 5];    //目标数组
//  a.remove(1);
//  type = "current"  指定目标， type="next"  指定目标之后
const removeArr = (type, arr, dx) => {
	const newArr = [];
	if (isNaN(dx) || dx > arr.length) {
		return false;
	}
	if (type == 'current') {
		arr.forEach((item, index) => {
			if (index != dx) {
				newArr.push(item);
			}
		});
	} else if (type == 'next') {
		arr.forEach((item, index) => {
			if (index <= dx) {
				newArr.push(item);
			}
		});
	}
	return newArr;
};

/**
  * removeObjKey， 删除对象指定得的key及值
  * @param  obj, 数据对象
  * @param  key值
  * @returns
  */
let removeObjKey = (obj, key) => {
	delete obj[key];
	return obj;
};

//从数据中随机取出几个元素
// arr  数组 ； count 个数
let getRandomArrayElements=(arr, count)=> {
    var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
    while (i-- > min) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled.slice(min);
}

//截取文件名格式（333.pdf）
let splitFileName=(text)=> {
    var fileExtension = text.substring(text.lastIndexOf('.') + 1);//截取文件后缀名
    var pattern = /\.{1}[0-9a-zA-Z]{1,}$/;
    if (pattern.exec(text) !== null) {
        return (text.slice(0, pattern.exec(text).index));
    } else {
        return text;
    }
}
 
let db = {
	//设置离线缓存
	setStroage: (key, data) => {
		uni.setStorageSync(key, data);
	},
	//获取离线缓存
	getStroage: (key) => {
		let data = uni.getStorageSync(key);
		return data;
	},
	//移除某个离线缓存
	removeStroage: (key) => {
		uni.removeStorageSync(key);
	},
	//移除所有离线缓存
	closeAllStroage: () => {
		uni.clearStorageSync();
	}
}

/**
 * getPagePath  返回当前的相对路径
 * path  当前页面的路径, 如 ：../../
 * return   ../../
 * */
let  getPagePath=(path)=>{
    let newPath = ''
    let index=0;
    let num=0;
    while(index!=-1)
    {
        index=path.indexOf('/',index);
        if(index!=-1) { num++ ; index++ ; newPath += '../'};
    } 
    return  newPath
}

// 获取缓存中的数据，当缓存大小超过6M,清除超过一个星期未更新的数据
// 要清除的数据主要为['teachListData','studyListData','teachAnalysisData','teachResultTotalData','studyAnalysisData']
let getStorageKey = (key,id) => {
    const storageArr = ['teachListData','studyListData','teachAnalysisData','teachResultTotalData','studyAnalysisData']
    wx.getStorageInfo({
        success (res) {
            if(res.currentSize > (res.limitSize - (1024 * 4)) ){
            // if(res.currentSize > 20 ){
                let arr = storageArr.filter(item => res.keys.includes(item))
                arr.forEach(item => {
                    let arr1 = wx.getStorageSync(item)
                    let arr2 = []
                    arr1.forEach(item1 => {
                        if(Date.now() - item1.time > 1000*60*60*24*7){
                        // if(Date.now() - item1.time > 1000*60*2){
                            
                        }else {
                            arr2.push(item1)
                        }
                    })
                    wx.setStorageSync(item,arr2)
                })
            }
        } 
    })
    let array = wx.getStorageSync(key) ? wx.getStorageSync(key) : []
    let obj = array.length > 0 ? array.filter(item => item.id == id) : {}
    let data = obj.length > 0 ? obj[0].data : null
    return data
}

//缓存数据
let setStorageKey = (key,id,data) => {
    let array = wx.getStorageSync(key) ? wx.getStorageSync(key) : []
    let index = -1
    let obj = {time:Date.now(), id:id, data:data}
    if(array.length > 0){
        array.forEach((item,num)=>{
            if(item.id == id){
                index = num
            }
        })
        if(index < 0){
            array.push(obj)
        }else {
            array.splice(index,1,obj)
        }
    }else {
        array.push(obj)
    }
    wx.setStorageSync(key,array)
}

// 判断输入的字符长度
let getCharLength = (value) => {
    let split = value.split('')
    let map = split.map((s, i) => {
        return (value.charCodeAt(i) >= 0 && value.charCodeAt(i) <= 128) ? 1 : 2;
    });
    let n = 0;
    const charLength = map.length > 0 && map.reduce((accumulator, currentValue, index) => { 
        const count = accumulator + currentValue;
        if (count === 31 || count === 32) {
            n = index;
        }
        return count
    });
    return charLength;
}

// 两个数之间的随机数
let getNumByRange=(start, end)=> {
    return Math.floor(Math.random() * (end - start) + start)
}

// 计时（从某个时间开始计时）
let timing = (h, m, s) => {
    let obj = { hour: '', minute: '', second: ''}
    s++
    if (s >= 60) {
        s = 0  //  大于等于60秒归零
        m++
        if (m >= 60) {
            m = 0  //  大于等于60分归零
            h++
            if (h < 10) {
                // 少于10补零   
                h = '0' + h
            }
        }
        if (m < 10) {
            // 少于10补零
            m = '0' + m
        }
    }
    if (s < 10) {
        // 少于10补零
        s = '0' + s
    }
    obj.hour =  h
    obj.minute=  m
    obj.second = s
    return obj
}

let OPENPPTWORDEXCEL=(filePath)=> {
    wx.openDocument({
        filePath: filePath,
        showMenu:true,
        success: function (res) {
            console.log(res,'打开文档成功')
        },
        fail: function (res) {
            console.log(res,'打开文档失败')
            wx.showToast({
                title: '打开文档失败!',
                icon: 'none',
                duration: 2000
            })
        },
        complete: function (res) {
            // console.log(res,'complete');
        }
    })
}

let handlePreview=(file,type)=> {
    let result = {
        mode:0// 0 office，1 other
    }
    let mimeType = fileType(type)
    return new Promise((resolve, reject) => {
        if(mimeType=='word'||mimeType=='ppt'||mimeType=='pdf'||mimeType=='excel'){
            result.mode=0;
        }else{
            result.mode=1;
        }
        resolve(result)
    })
}

module.exports = {
	formatTime: formatTime,
	onFmoney: onFmoney,
	triggerPrePagefun: triggerPrePagefun,
	mimeTypejup: mimeTypejup,
	toErroPage,
	delobjKey,
	getUrlParams,
	turnUrlData,
	diffTime,
	diffTime1,
	setTimer,
	clearTimer,
	subStrName,
	randomString,
	bytesToSize,
    removeArr,
    getRandomArrayElements,
    splitFileName,
    getPagePath,
    fileType,
    getStorageKey,
    setStorageKey,
    getCharLength,
    getNumByRange,
    timing,
    OPENPPTWORDEXCEL,
    handlePreview
};
